package com.demo.esjd.utils;

import com.demo.esjd.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtil {
//    public  static  void  main(String[] arg) throws IOException {
//
//            new HtmlParseUtil().parseJD("java").forEach(System.out::println);
//    }

    public List<Content> parseJD(String keywords) throws IOException
    {
        String url="https://search.jd.com/Search?keyword="+keywords;

        Document document = Jsoup.parse(new URL(url), 30000);

        Element j_goodsList = document.getElementById("J_goodsList");

//        System.out.println(j_goodsList.html());

        Elements li = j_goodsList.getElementsByTag("li");

        List<Content> contents = new ArrayList<>();

        for (Element element : li) {
            String img = element.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = element.getElementsByClass("p-price").eq(0).text();
            String name = element.getElementsByClass("p-name").eq(0).text();

            contents.add(new Content(name,img,price));
        }

        return  contents;
    }
}
